package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.push.JPushClientService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * <desc>
 *      物业缴费生成账单极光推送业务操作队列消费者
 * </desc>
 *
 * @createDate 16:49 2017-11-30
 */
@Component
public class PaymentBillJPushConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(PaymentBillJPushConsumer.class);

    @Autowired
    JPushClientService jPushClientService;


    /**
     * <desc>
     *      推送物业缴费生成账单极光推送消息
     * </desc>
     *
     * @param message 消息
     * @param channel
     * @return
     * @author Jiaqi.X
     * @createDate 2018/08/31
     */
    @RabbitListener(queues =RabbitMQConstant.RABBITMQ_PAYMENT_BILL_JPUSH_QUEUE)
    public void process(Message message, Channel channel) throws InterruptedException, IOException {
        byte[] body = message.getBody();
        LOG.info("RabbitMQ_物业住户迁入/迁出/审核时极光推送业务消费端:"+body);
        try {
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JSON.parseObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            JSONObject dataJs = JSON.parseObject(timeTaskDeadMessageQueuePO.getMessageContent());
            String projectId = dataJs.getString("projectId");
            for(String phone:JsonUtil.decode(dataJs.getString("phoneNum"), new TypeReference<List<String>>() {})) {
                jPushClientService.pushWithTaskForBillTO(phone, "ServicePay", dataJs.getString("message"), projectId, dataJs.getString("feeId"));
            }
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_物业住户极光推送业务消费端】:解析异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
